/**
 * Created by wdj on 16/4/21.
 * app
 */

var hybrid = require('../libs/hybrid');
var utils = require('../libs/utils');

require('framework7');
require('framework7/dist/css/framework7.ios.css');
require('framework7/dist/css/framework7.ios.colors.css');
require('../css/app.css');
require('animate.css');

var $ = Dom7;

var ctls = [];

var loadPage = (viewName) => {
    return require('../pages/' + viewName);
};

function checkLogin() {
    return false
}

class App {

    constructor(customOptions, customViewOptions) {

        var options = {};
        [
            'onPageBeforeInit',
            'onPageInit',
            'onPageBeforeAnimation',
            'onPageAfterAnimation',
            'onPageBeforeRemove',
            'onPageBack',
            'onPageAfterBack',
        ].forEach(function (name) {
            options[name] = (app, page) => {

                if('onPageAfterAnimation' === name || 'onPageBeforeInit' === name){
                    App.isDebug() && console.log("%c[DEBUG] %c" + page.name + ' ' + name, "color: #ff6600", "color: green");
                    var pageName = page.view ? page.view.container.getAttribute('data-page') : 'index';
                    document.body.setAttribute('data-page-name', pageName);
                }

                if(page.name){
                    var ctl = App.loadController(app, page);
                    if(ctl && typeof ctl[name] === 'function'){
                        ctl[name](app, page);
                    }
                }
            };
        });

        var self = this;
        utils.extend(options, {
            // statusbarOverlay: ((Native.device.android && Native.device.osVersion >= '4.4' && (window.ANDROID_TRANSLUCENT_STATUS_BAR )) || Native.device.ios) && Native.device.isNative,
            scrollTopOnStatusbarClick: true,
            animateNavBackIcon: true,
            swipeBackPage: true,
            swipeBackPageActiveArea: window.innerWidth / 4,
            swipeBackPageAnimateShadow: false,
            swipeBackPageAnimateOpacity: false,
            uniqueHistory: true,
            swipePanel: 'left',
            scrollTopOnNavbarClick: true,
            modalButtonOk: '确认',
            modalButtonCancel: '取消',
            modalUsernamePlaceholder: '用户名',
            modalPasswordPlaceholder: '密码',
            modalTitle: '毛遂自荐',
            modalPreloaderTitle: '加载中...',
            notificationCloseButtonText: '关闭',
            hardwareBtnBack: true,
            preroute: function (view, options) {

                if(options && options.url && /pages.*?\.jade/.test(options.url)){
                    var url = options.url;
                    if(~url.indexOf('?')){
                        url = url.split('?')[0];
                    }
                    if(/^pages/.test(url)){
                        url = url.substr(6)
                    }
                    var jade = loadPage(url);
                    var query = $.parseUrlQuery(options.url);

                    view.router.load({
                        content: jade(query),
                        query: query
                    });

                    return false;
                }else if(options && options.content){

                    if(options.content.match(/data-login="required"/) && !checkLogin()){
                        if(App.isDebug()){
                            var pageName = options.content.match(/data-page="(.*?)"/)[1];
                            console.warn(`访问的页面 ${pageName} 需要登陆, 跳转到 login 页面。`);
                        }
                        var formUrl = options.formUrl;
                        view.loadPage('pages/login.jade' + ( formUrl ? '?fromUrl=' + encodeURIComponent(formUrl) : ''));
                        return false;
                    }
                }

                //处理分享url
                if(options && options.url && options.url.indexOf('_shareUid') > -1){
                    var queryParams = $.parseUrlQuery(options.url);
                    utils.Storage.set('shareUid', queryParams['_shareUid']);
                }
            }
        });
        utils.extend(options, customOptions);

        this.app = new Framework7(options);

        var viewOptions = {
            domCache: true, //enable inline pages
            dynamicNavbar: true
        };
        utils.extend(viewOptions, customViewOptions);

        this.view = this.app.addView('.view-main',  viewOptions);
        this.initialApp();
    }

    initialApp() {
        var app = this.app;

        utils.extend(this.app, {
            query: $
        });

        if(hybrid.isNative){
            try{
                document.documentElement.style.webkitTouchCallout = "none";
                document.documentElement.style.webkitUserSelect = "none";
            }catch(e){}

            var lastClickBackButton = 0;
            hybrid.addEventListener('btnBack', function () {

                //点击返回的是否如果有modal被打开就先关闭所有打开的modal
                if($('.modal-in').length || $('.photo-browser-in').length){
                    app.closeModal();
                    return;
                }

                if(app.mainView.activePage.name === 'index'){
                    if(Date.now() - lastClickBackButton < 3000){
                        hybrid.finish();
                        console.log('finish');
                        lastClickBackButton = 0;
                    }else{
                        app.showToast('再按一次退出app');
                    }
                    lastClickBackButton = Date.now();
                }else{
                    if(app.mainView.params.hardwareBtnBack){
                        app.mainView.router.back();
                    }
                }
            });
        }

    }

    static loadController(app, page){
        var name = page.name;
        if(ctls[name]){
            return ctls[name];
        }

        // console.log(name + ' init controller.');
        var Ctl = require('./controller/' + utils.ucfirst(name) +'Controller');
        //console.log( Ctl);
        if(Ctl.default){
            Ctl = Ctl.default;
        }
        return ctls[name] = new Ctl(app, page);
    }

    static run(customOptions, customViewOptions){
        App.isDebug() && App.showDevelopMenu();
        return new App(customOptions, customViewOptions);
    }

    static showDevelopMenu(){
        // var eruda = require('eruda');
        // eruda.init();
    }

    static isDebug(){
        return 1
    }
}

export default App.run();
